// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package logger

import (
	"bytes"

	"github.com/kumose/kmopt/pkg/cluster/audit"
	"github.com/kumose/kmopt/pkg/utils"
	"go.uber.org/atomic"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var auditEnabled atomic.Bool
var auditBuffer *bytes.Buffer
var auditDir string

// EnableAuditLog enables audit log.
func EnableAuditLog(dir string) {
	auditDir = dir
	auditEnabled.Store(true)
}

// DisableAuditLog disables audit log.
func DisableAuditLog() {
	auditEnabled.Store(false)
}

func newAuditLogCore() zapcore.Core {
	auditBuffer = bytes.NewBuffer([]byte{})
	encoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())
	return zapcore.NewCore(encoder, zapcore.Lock(zapcore.AddSync(auditBuffer)), zapcore.DebugLevel)
}

// OutputAuditLogToFileIfEnabled outputs audit log to specified fileSuffix if enabled.
func OutputAuditLogToFileIfEnabled(dir, fileSuffix string) error {
	if !auditEnabled.Load() {
		return nil
	}

	if err := utils.MkdirAll(dir, 0755); err != nil {
		return err
	}

	err := audit.OutputAuditLog(dir, fileSuffix, auditBuffer.Bytes())
	if err != nil {
		return err
	}

	if dir == auditDir {
		auditBuffer.Reset()
	}

	return nil
}

// OutputAuditLogIfEnabled outputs audit log if enabled.
func OutputAuditLogIfEnabled() error {
	return OutputAuditLogToFileIfEnabled(auditDir, "")
}
